<article id="wikiArticle">
<div></div>
<h2 id="概述">概述</h2>
<p><code><strong>encodeURIComponent()</strong></code>是对统一资源标识符（URI）的组成部分进行编码的方法。它使用一到四个转义序列来表示字符串中的每个字符的UTF-8编码（只有由两个Unicode代理区字符组成的字符才用四个转义字符编码）。</p>
<h2 id="语法">语法</h2>
<pre><code class="language-javascript">encodeURIComponent(str);</code></pre>
<h3 id="参数">参数</h3>
<dl>
<dt><code>str</code></dt>
<dd>String. URI 的组成部分。</dd>
</dl>
<h2 id="描述">描述</h2>
<p><code>encodeURIComponent</code> 转义除了字母、数字、<code>(</code>、<code>)</code>、<code>.</code>、<code>!</code>、<code>~</code>、<code>*</code>、<code>'</code>、<code>-</code>和<code>_</code>之外的所有字符。</p>
<p>注意，如果试图编码一个非高-低位完整的代理字符，将会抛出一个 <a href="Reference/Global_Objects/URIError" title="URIError 对象用来表示以一种错误的方式使用全局URI处理函数而产生的错误。"><code>URIError</code></a> 错误，例如：</p>
<pre><code  class="language-javascript">// 高低位完整
alert(encodeURIComponent('\uD800\uDFFF'));

// 只有高位，将抛出"URIError: malformed URI sequence"
alert(encodeURIComponent('\uD800'));

// 只有低位，将抛出"URIError: malformed URI sequence"
alert(encodeURIComponent('\uDFFF')); </code></pre>
<p>为了避免服务器收到不可预知的请求，对任何用户输入的作为URI部分的内容你都需要用encodeURIComponent进行转义。比如，一个用户可能会输入"<code>Thyme &amp;time=again</code>"作为<code>comment</code>变量的一部分。如果不使用encodeURIComponent对此内容进行转义，服务器得到的将是<code>comment=Thyme%20&amp;time=again</code>。请注意，"&amp;"符号和"="符号产生了一个新的键值对，所以服务器得到两个键值对（一个键值对是<code>comment=Thyme</code>，另一个则是<code>time=again</code>），而不是一个键值对。</p>
<p>对于 <a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#application/x-www-form-urlencoded-encoding-algorithm" rel="noopener"><code>application/x-www-form-urlencoded</code></a> (POST) 这种数据方式，空格需要被替换成 '+'，所以通常使用 <code>encodeURIComponent</code> 的时候还会把 "%20" 替换为 "+"。</p>
<p>为了更严格的遵循 <a class="external" href="http://tools.ietf.org/html/rfc3986" rel="noopener">RFC 3986</a>（它保留 !, ', (, ), 和 *），即使这些字符并没有正式划定 URI 的用途，下面这种方式是比较安全的：</p>
<pre><code  class="language-javascript">function fixedEncodeURIComponent (str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}</code></pre>
<h2 id="示例">示例</h2>
<p>下面这个例子提供了 UTF-8 下 <code>Content-Disposition</code> 和 <code>Link</code> 的服务器响应头信息的参数（例如 UTF-8 文件名)：</p>
<pre><code  class="language-javascript">var fileName = 'my file(2).txt';
var header = "Content-Disposition: attachment; filename*=UTF-8''" 
             + encodeRFC5987ValueChars(fileName);

console.log(header); 
// 输出 "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"


function encodeRFC5987ValueChars (str) {
    return encodeURIComponent(str).
        // 注意，仅管 RFC3986 保留 "!"，但 RFC5987 并没有
        // 所以我们并不需要过滤它
        replace(/['()]/g, escape). // i.e., %27 %28 %29
        replace(/\*/g, '%2A').
            // 下面的并不是 RFC5987 中 URI 编码必须的
            // 所以对于 |`^ 这3个字符我们可以稍稍提高一点可读性
            replace(/%(?:7C|60|5E)/g, unescape);
}
</code></pre>
<h2 id="规范">规范</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">规范</th>
<th scope="col">状态</th>
<th scope="col">备注</th>
</tr>
<tr>
<td><a class="external" href="https://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf" hreflang="en" lang="en" rel="noopener" title="ECMAScript 3rd Edition (ECMA-262)">ECMAScript 3rd Edition (ECMA-262)</a></td>
<td><span class="spec-Standard">Standard</span></td>
<td>初始定义</td>
</tr>
<tr>
<td><a class="external" href="https://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3.4" hreflang="en" lang="en" rel="noopener">ECMAScript 5.1 (ECMA-262)<br/><small lang="zh-CN">encodeURIComponent</small></a></td>
<td><span class="spec-Standard">Standard</span></td>
<td> </td>
</tr>
<tr>
<td><a class="external" href="https://www.ecma-international.org/ecma-262/6.0/#sec-encodeuricomponent-uricomponent" hreflang="en" lang="en" rel="noopener">ECMAScript 2015 (6th Edition, ECMA-262)<br/><small lang="zh-CN">encodeURIComponent</small></a></td>
<td><span class="spec-Standard">Standard</span></td>
<td> </td>
</tr>
<tr>
<td><a class="external" href="https://tc39.github.io/ecma262/#sec-encodeuricomponent-uricomponent" hreflang="en" lang="en" rel="noopener">ECMAScript Latest Draft (ECMA-262)<br/><small lang="zh-CN">encodeURIComponent</small></a></td>
<td><span class="spec-Draft">Draft</span></td>
<td> </td>
</tr>
</tbody>
</table>
<h2 id="浏览器兼容性">浏览器兼容性</h2>
<p></p><div class="blockIndicator warning"><strong><a class="external" href="https://github.com/mdn/browser-compat-data" rel="noopener">We're converting our compatibility data into a machine-readable JSON format</a></strong>.
            This compatibility table still uses the old format,
            because we haven't yet converted the data it contains.
            <strong><a class="new" href="/zh-CN/docs/MDN/Contribute/Structures/Compatibility_tables" rel="nofollow">Find out how you can help!</a></strong></div>
<div class="htab">
<a id="AutoCompatibilityTable" name="AutoCompatibilityTable"></a>
<ul>
<li class="selected"><a>Desktop</a></li>
<li><a>Mobile</a></li>
</ul>
</div><p></p>
<div id="compat-desktop">
<table class="compat-table">
<tbody>
<tr>
<th>特性</th>
<th>Chrome</th>
<th>Firefox (Gecko)</th>
<th>Internet Explorer</th>
<th>Opera</th>
<th>Safari</th>
</tr>
<tr>
<td>基础功能</td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
</tr>
</tbody>
</table>
</div>
<div id="compat-mobile">
<table class="compat-table">
<tbody>
<tr>
<th>特性</th>
<th>Android</th>
<th>Chrome for Android</th>
<th>Firefox Mobile (Gecko)</th>
<th>IE Mobile</th>
<th>Opera Mobile</th>
<th>Safari Mobile</th>
</tr>
<tr>
<td>基础功能</td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
<td><span style="color: #888;" title="Please update this with the earliest version of support.">(Yes)</span></td>
</tr>
</tbody>
</table>
</div>
<h2 id="相关链接">相关链接</h2>
<ul>
<li><a href="Reference/Global_Objects/decodeURI" title="decodeURI() 函数解码一个由encodeURI 先前创建的统一资源标识符（URI）或类似的例程。"><code>decodeURI</code></a></li>
<li><a href="Reference/Global_Objects/encodeURI" title='encodeURI()  函数通过将特定字符的每个实例替换为一个、两个、三或四转义序列来对统一资源标识符 (URI) 进行编码 (该字符的 UTF-8 编码仅为四转义序列)由两个 "代理" 字符组成)。'><code>encodeURI</code></a></li>
<li><a href="Reference/Global_Objects/decodeURIComponent" title="decodeURIComponent() 方法用于解码由 encodeURIComponent 方法或者其它类似方法编码的部分统一资源标识符（URI）。"><code>decodeURIComponent</code></a></li>
</ul>
<p></p>
</article>